'''
Created on 14 juin 2013

@author: Nils Amiet
'''

# coding: utf-8

import networkx as nx
import sqlite3

class InfrarougeGraphBuilder():
    
    userRepliesCounts = {}
    graph1 = nx.DiGraph()
    
    userParticipations = []
    graph2 = nx.Graph()
       
    def __init__(self, databasePath):
        self.infrarougeDatabasePath = databasePath
        
        self.countUserReplies()
        self.createRepliesGraph()
        self.buildUserParticipations()
        self.createParticipationGraph()
    
    def countUserReplies(self):    
        with sqlite3.connect(self.infrarougeDatabasePath) as connection:
            cursor = connection.cursor()
            
            query = "SELECT * FROM reply"
            cursor.execute(query)
            
            for reply in cursor:
                self.countReply(reply)
            
            cursor.close()
            
    def countReply(self, reply):
        fromUser = reply[0]
        toUser = reply[1]
        
        fromTo = (fromUser, toUser)
        try:
            self.userRepliesCounts[fromTo] += 1
        except KeyError:
            self.userRepliesCounts[fromTo] = 1
            
    def createRepliesGraph(self):    
        for fromTo, w in self.userRepliesCounts.items():
            try:
                self.graph1.add_edge(fromTo[0], fromTo[1], weight=w)
            except:
                print("Warning: adding edge failed")
        
    def buildUserParticipations(self):       
        with sqlite3.connect(self.infrarougeDatabasePath) as connection:
            cursor = connection.cursor()
            
            query = "SELECT * FROM threadmessage"
            cursor.execute(query)
            
            for threadMessage in cursor:
                forumThread = threadMessage[2]
                user = threadMessage[3]
                userThreadTuple = (user, forumThread)
                self.userParticipations += [userThreadTuple]
            
            cursor.close()
            
    def createParticipationGraph(self):
        users = [x[0] for x in self.userParticipations]
        discussions = [x[1] for x in self.userParticipations]
    
        self.graph2.add_nodes_from(users, bipartite=0)
        self.graph2.add_nodes_from(discussions, bipartite=1)
        self.graph2.add_edges_from(self.userParticipations)

